﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Threading;
using ValuationLogic;
using ValuationResource;

namespace ValuationUI
{

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public Thread refreshThread,dataStatusThread,updateRiskExThread;
        //public Thread dataStatusThread=new Thread(new ThreadStart(refreshDataStatus));
        public Swap theSwap = new Swap();
        public RiskViewForm riskView = null;
        public static List<Swap> allSwapTradList = Logic.getSwaps(LoginForm.userOnlineID);
        //LoginForm myLoginForm=new LoginForm();

        public MainWindow()
        {
            InitializeComponent();
            disableAddTrade();

            //myLoginForm = myLogin;
            riskView = new RiskViewForm();
            riskView.WindowStartupLocation = WindowStartupLocation.Manual;
            riskView.Show();
            Logic.StartForRefreshData(ref refreshThread);
            dataStatusThread = new Thread(new ThreadStart(refreshDataStatus));
            dataStatusThread.Start();
            updateRiskExThread = new Thread(new ThreadStart(checkRiskEx));
            updateRiskExThread.Start();
        }
        //private delegate void DoTask();
        //private void Start()
       // {
          //  System.Windows.Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new DoTask(refreshDataStatus));
       // }

        private void refreshDataStatus()
        {
            while (true)
            {
                bool dataStatus = Logic.refreshDone;
                Dispatcher.Invoke((Action)delegate() {
                    showRefreshStatus(dataStatus);
                });
                while (dataStatus == Logic.refreshDone)
                {
                    Thread.Sleep(1000);
                }
            }
        }

        private void showRefreshStatus(bool status){
            if (status)
            {
                this.refreshLabel.Content = "更新完毕";
            }
            else
            {
                this.refreshLabel.Content = "更新中……";
            }
        }
        
        private void checkRiskEx()
        {
            while (true)
            {
                DateTime date = Logic.getCurDate();
                Dispatcher.Invoke((Action)delegate()
                {
                    updateRX();
                });
                while (EqualsYearMonthDay(date, Logic.getCurDate()))
                {
                    Thread.Sleep(1000);

                }
            }
        }

        private void updateRX()
        {
            this.riskView.updatePnL_Click();
        }
         

        private bool EqualsYearMonthDay(DateTime date1, DateTime date2)
        {
            return ((date1.Year == date2.Year) && (date1.Month == date2.Month) && (date1.Day == date2.Day));
        }

        private void enableAddTrade()
        {
            this.counterpartyNameTextBox.IsEnabled = true;
            this.buyFixedComboBox.IsEnabled = true;
            this.commodityUnitComboBox.IsEnabled = true;
            this.currencyUnitComboBox.IsEnabled = true;
            this.fixedPriceTextBox.IsEnabled = true;
            this.periodStartDatePicker.IsEnabled = true;
            this.periodEndDatePicker.IsEnabled = true;
            this.quantityTextBox.IsEnabled = true;
            this.quantityUnitComboBox.IsEnabled = true;
            this.floatingQuoteCodeComboBox.IsEnabled = true;
            this.dealDatePicker.IsEnabled = true;
            this.addTradeBtn.IsEnabled = false;
            this.submitTradeBtn.IsEnabled = true;
            this.cancelTradeBtn.IsEnabled = true;
        }
        private void disableAddTrade()
        {
            this.counterpartyNameTextBox.IsEnabled = false;
            this.counterpartyNameTextBox.Text = "";
            this.buyFixedComboBox.IsEnabled = false;
            this.buyFixedComboBox.SelectedIndex = 0;
            this.commodityUnitComboBox.IsEnabled = false;
            this.commodityUnitComboBox.SelectedIndex = 0;
            this.currencyUnitComboBox.IsEnabled = false;
            this.currencyUnitComboBox.SelectedIndex = 0;
            this.fixedPriceTextBox.IsEnabled = false;
            this.fixedPriceTextBox.Text = "";
            this.periodStartDatePicker.IsEnabled = false;

            this.periodEndDatePicker.IsEnabled = false;
            #region 双休日不可选；enddate在startdate之后
            #endregion
            if ((int)DateTime.Now.DayOfWeek == 6)
            {
                periodStartDatePicker.SelectedDate = DateTime.Now.AddDays(2);
                periodEndDatePicker.SelectedDate = DateTime.Now.AddDays(3);
            }
            else if ((int)DateTime.Now.DayOfWeek == 0)
            {
                periodStartDatePicker.SelectedDate = DateTime.Now.AddDays(1);
                periodEndDatePicker.SelectedDate = DateTime.Now.AddDays(2);
            }
            else if ((int)DateTime.Now.DayOfWeek == 5)
            {
                periodStartDatePicker.SelectedDate = DateTime.Now;
                #region 这句话执行了4次
                #endregion
                periodEndDatePicker.SelectedDate = DateTime.Now.AddDays(3);
            }
            else
            {
                periodStartDatePicker.SelectedDate = DateTime.Now;
                periodEndDatePicker.SelectedDate = DateTime.Now.AddDays(1);
                /*
                 *日期改变会显示多余的信息。开始结束时间可能不合逻辑
                 */
            }
            this.quantityTextBox.IsEnabled = false;
            this.quantityTextBox.Text = "";
            this.quantityUnitComboBox.IsEnabled = false;
            this.quantityUnitComboBox.SelectedIndex = 0;
            this.floatingQuoteCodeComboBox.IsEnabled = false;
            this.floatingQuoteCodeComboBox.SelectedIndex = 0;
            this.dealDatePicker.IsEnabled = false;
            this.dealDatePicker.SelectedDate = DateTime.Now;
            this.addTradeBtn.IsEnabled = true;
            this.submitTradeBtn.IsEnabled = false;
            this.cancelTradeBtn.IsEnabled = false;
        }

        private void quitBtn_Click(object sender, RoutedEventArgs e)
        {
            if (allSwapTradList != null)
            {
                allSwapTradList.Clear();
            }
            refreshThread.Abort();
            dataStatusThread.Abort();
            updateRiskExThread.Abort();
            this.Hide();
            riskView.Close();
            this.Close();
            this.Owner.Show();
        }

        private void addTradeBtn_Click(object sender, RoutedEventArgs e)
        {
            enableAddTrade();
        }

        private void quantityTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (quantityTextBox.Text.Length == 0)
            {
                return;
            }
            string numText = "";
            for (int i = 0; i < quantityTextBox.Text.Length; i++)
            {
                if ((char)quantityTextBox.Text[i] >= '0' && (char)quantityTextBox.Text[i] <= '9')
                {
                    numText = numText + quantityTextBox.Text[i].ToString();
                }
                else if ((char)quantityTextBox.Text[i] == '.')
                {
                    numText = numText + ".";
                    for (int m = i + 1; m < quantityTextBox.Text.Length; m++)
                    {
                        if ((char)quantityTextBox.Text[m] >= '0' && (char)quantityTextBox.Text[m] <= '9')
                        {
                            numText = numText + quantityTextBox.Text[m].ToString();
                        }
                    }
                    if (numText.Length > 0 && numText[0] == '.')
                    {
                        numText = numText.Remove(0, 1);
                    }
                    this.quantityTextBox.Text = numText;
                    return;
                }
            }
            if (numText.Length > 0 && numText[0] == '.')
            {
                numText = numText.Remove(0, 1);
            }
            this.quantityTextBox.Text = numText;
            return;

        }

        private void fixedPriceTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (fixedPriceTextBox.Text.Length == 0)
            {
                return;
            }
            string numText = "";
            for (int i = 0; i < fixedPriceTextBox.Text.Length; i++)
            {
                if ((char)fixedPriceTextBox.Text[i] >= '0' && (char)fixedPriceTextBox.Text[i] <= '9')
                {
                    numText = numText + fixedPriceTextBox.Text[i].ToString();
                }
                else if ((char)fixedPriceTextBox.Text[i] == '.')
                {
                    numText = numText + ".";
                    for (int m = i + 1; m < fixedPriceTextBox.Text.Length; m++)
                    {
                        if ((char)fixedPriceTextBox.Text[m] >= '0' && (char)fixedPriceTextBox.Text[m] <= '9')
                        {
                            numText = numText + fixedPriceTextBox.Text[m].ToString();
                        }
                    }
                    if (numText.Length > 0 && numText[0] == '.')
                    {
                        numText = numText.Remove(0, 1);
                    }
                    this.fixedPriceTextBox.Text = numText;
                    return;
                }
            }
            if (numText.Length > 0 && numText[0] == '.')
            {
                numText = numText.Remove(0, 1);
            }
            this.fixedPriceTextBox.Text = numText;
            return;

        }

        private void submitTradeBtn_Click(object sender, RoutedEventArgs e)
        {
            theSwap = new Swap();
            Logic.setCurDate(new DateTime());
            theSwap.setBuyFixed(this.buyFixedComboBox.SelectedIndex == 0);
            if (this.counterpartyNameTextBox.Text.Trim().Length == 0)
            {
                MessageBox.Show(this, "ERROR! CounterpartyName can't be null");
                return;
            }
            theSwap.setCounterparty(this.counterpartyNameTextBox.Text);
            if (this.currencyUnitComboBox.SelectedIndex == 0)
            {
                theSwap.setCurrencyUnit("USD");
            }

            theSwap.setDealDate((DateTime)this.dealDatePicker.SelectedDate);
            if (this.fixedPriceTextBox.Text.Trim().Length == 0)
            {
                MessageBox.Show(this, "ERROR! Fixed price can't be null");
                return;
            }
            if (this.commodityUnitComboBox.SelectedIndex == 0)
            {
                theSwap.setCommodityUnit("BBL");
                theSwap.setFixedPrice(double.Parse(this.fixedPriceTextBox.Text));
            }
            else if (this.commodityUnitComboBox.SelectedIndex == 1)
            {
                theSwap.setCommodityUnit("lot");
                theSwap.setFixedPrice(double.Parse(this.fixedPriceTextBox.Text) * 1000);

            }

            theSwap.setPeriodStartDate((DateTime)this.periodStartDatePicker.SelectedDate);
            theSwap.setPeriodEndDate((DateTime)this.periodEndDatePicker.SelectedDate);

            if (this.quantityTextBox.Text.Trim().Length == 0)
            {
                MessageBox.Show(this, "ERROR! Quantity can't be null");
                return;
            }
            if (this.quantityUnitComboBox.SelectedIndex == 0)
            {
                theSwap.setQuantity(float.Parse(this.quantityTextBox.Text));
            }
            else
            {
                theSwap.setQuantity(float.Parse(this.quantityTextBox.Text) * 1000);
            }
            if (this.floatingQuoteCodeComboBox.SelectedIndex == 0)
            {

                theSwap.setQuoteCode("WTI");
            }
            if (!periodStartDatePicker_SelectedDateChanged() || !periodEndDatePicker_SelectedDateChanged())
            {
                return;
            }
            if (!Logic.addSwap(theSwap))
            {
                MessageBox.Show(this, "Add swap ERROR");
                return;
            }
            disableAddTrade();

            Logic.setCurDate(DateTime.Now);
            //刷新显示
            this.riskView.tradeViewUpdate(theSwap);
        }

        private void cancelTradeBtn_Click(object sender, RoutedEventArgs e)
        {
            disableAddTrade();
        }

        private void viewRiskBtn_Click(object sender, RoutedEventArgs e)
        {
            //showTheContacts(this.tradeView);
            //this.swapTradeListView.SelectedIndex
            if (riskView != null && riskView.IsVisible == true)
            {
                riskView.Hide();
            }


            else if (riskView != null && riskView.IsVisible == false)
            {
                riskView.WindowStartupLocation = WindowStartupLocation.Manual;
                riskView.Left = this.Left + this.Width;
                riskView.Top = this.Top + (this.Height - riskView.Height) / 2;
                try
                {
                    riskView.Show();
                }
                catch (InvalidOperationException)
                {
                    riskView = new RiskViewForm();
                    riskView.Owner = this;
                    riskView.WindowStartupLocation = WindowStartupLocation.Manual;
                    riskView.Left = this.Left + this.Width;
                    riskView.Top = this.Top + (this.Height - riskView.Height) / 2;
                    //riskView.tradeViewInit();
                    riskView.Show();

                }
            }

            else if (riskView == null)
            {
                riskView = new RiskViewForm();
                riskView.Owner = this;
                riskView.WindowStartupLocation = WindowStartupLocation.Manual;
                riskView.Left = this.Left + this.Width;
                riskView.Top = this.Top + (this.Height - riskView.Height) / 2;
                riskView.Show();
            }
        }


        private bool periodStartDatePicker_SelectedDateChanged()
        {
            DateTime selectedDate = (DateTime)this.periodStartDatePicker.SelectedDate;
            if ((int)selectedDate.DayOfWeek == 6 || (int)selectedDate.DayOfWeek == 0)
            {
                MessageBox.Show(this, "The start date is weekend!");
                return false;
            }
            else if (this.periodStartDatePicker.SelectedDate > this.periodEndDatePicker.SelectedDate)
            {
                MessageBox.Show(this, "The start date is later than end date");
                return false;
            }
            else if (this.periodStartDatePicker.SelectedDate == this.periodEndDatePicker.SelectedDate)
            {
                MessageBox.Show(this, "The start date equals the end date");
                return false;
            }
            return true;
        }

        private bool periodEndDatePicker_SelectedDateChanged()
        {
            DateTime selectedDate = (DateTime)this.periodEndDatePicker.SelectedDate;
            if ((int)selectedDate.DayOfWeek == 6 || (int)selectedDate.DayOfWeek == 0)
            {
                MessageBox.Show(this, "The end date is weekend!");
                return false;
            }
            else if (this.periodStartDatePicker.SelectedDate > this.periodEndDatePicker.SelectedDate)
            {
                MessageBox.Show(this, "This is earlier than start date");
                return false;
            }
            else if (this.periodStartDatePicker.SelectedDate == this.periodEndDatePicker.SelectedDate)
            {
                MessageBox.Show(this, "This equals the start date ");
                return false;
            }
            return true;
        }



        private void Window_LocationChanged(object sender, EventArgs e)
        {
            riskView.Top = this.Top;
            riskView.Left = this.Left + this.Width;
        }
        /*
        public void loading()
        {
            Thread thread1 = new Thread(beginImport);
        }

        public delegate void UpdateProgressBarDelegate
(System.Windows.DependencyProperty dp, Object value);

        public void beginImport()
        {
            this.updateProgressBar.Maximum = 100;
            this.updateProgressBar.Value = 0;

            UpdateProgressBarDelegate updatePbDelegate =
 new UpdateProgressBarDelegate(this.updateProgressBar.SetValue);

            for (int i=1;i<100;i++)
            {
                Dispatcher.Invoke(updatePbDelegate, System.Windows.
      Threading.DispatcherPriority.Background, new object[] 
{ System.Windows.Controls.ProgressBar.
ValueProperty,Convert.ToDouble(i + 1) });
            }
        } */
    }
}
